import axios from 'axios';
import { ElMessageBox } from 'element-plus';
import { Session } from '/@/utils/storage';

// 配置新建一个 axios 实例
const service = axios.create({
	baseURL: import.meta.env.VITE_API_URL as any,
	timeout: 50000,
	headers: {
		"Content-Type": "application/json"
	}
});
service.interceptors.request.use(
	(config) => {
		if (Session.get('token')) {
			config.headers.common['Authorization'] = `Bearer ${Session.get('token')}`;
		}
		return config;
	},
	(error) => {
		return Promise.reject(error);
	}
);
service.interceptors.response.use(
	(response) => {
		const res = response.data;
		return res;
	},
	(error) => {
		if (error.response && error.response !== 'undefined') {
			if (error.response.status === 201) {
				ElMessageBox.alert(error.response.data, '提示', {})
					.then(() => { }).catch(() => { });
			}
			if (error.response.status === 401) {
				Session.clear();
				ElMessageBox.alert("身份已过期，请重新授权！", '提示', {})
					.then(() => {
						window.location.href = '/';
					}).catch(() => { });
			}
			if (error.response.status === 500) {
				ElMessageBox.alert(error.response.data, '提示', {}).then(() => {
					window.location.href = '/';
				 }).catch(() => { });
			}
		} else {
			ElMessageBox.alert(error, '提示', {}).then(() => { }).catch(() => {
				window.location.href = '/';
			 });
		}
		return Promise.reject(error);
	}
);
export default service;
